import React, { Component } from 'react'
import axios from 'axios'
import './checkrole.scss'
import { Table, Tag, Space, Button, Popconfirm, Modal, Form, Input, Checkbox, notification, message } from 'antd';
import { nanoid } from 'nanoid'
import menuList from '../../../config/menuConfig'


import api from '../../../api'

const CheckboxGroup = Checkbox.Group;


export default class CheckRole extends Component {
    formRef = React.createRef()
    state = {
        listData: [],
        isModalVisible: false,
        itemId: 0,
        formItemLayout: {
            labelCol: {
                xs: {
                    span: 24,
                },
                sm: {
                    span: 4,
                },
            },
            wrapperCol: {
                xs: {
                    span: 24,
                },
                sm: {
                    span: 20,
                },
            },
        },
    }
    hideModle = () => {
        this.setState({ isModalVisible: false })
    }
    showModle = (id) => {
        return () => {
            console.log(id);
            this.setState({ isModalVisible: true, itemId: id })
        }

    }
    //编辑
    editRole = () => {
        const { listData, itemId } = this.state
        this.formRef.current.validateFields().then( async (values) => {
            let time = new Date().toLocaleString();
            values.time = time;
            values.id = itemId;
            values = { ...values, author: JSON.stringify(values.author) }
            let res = await api.role.editrole(values)
            console.log(res);
            if (res.data.status === 0) {//与后端代码有关res.send()
                const newList = listData.map((item)=>{
                    if(item.id === itemId){
                        return { ...item,key: nanoid(), name:values.rolename,create_time:values.time,autharr:JSON.parse(values.author)}
                    } else {
                        return item
                    }
                })
                this.setState({ listData: newList, isModalVisible: false })
                notification.open({
                    message: '修改成功',
                    description:
                        '太强了',
                    onClick: () => {
                        console.log('Notification Clicked!');
                    },
                });
            } else {
                message.error(res.data.msg)
            }
        })

    }
    //删除
    deleteItem = (id) => {
        const { listData } = this.state
        return async () => {
            let res = await api.role.delrole(id)
            console.log(res);
            if (res.data.status === 0) {
                const newList = listData.filter((item) => {
                    return item.id !== id
                })
                //更新状态
                this.setState({ listData: newList })
            }
        }
    }
    async componentDidMount() {
        const { listData } = this.state
        let roledata = await api.role.roledata()
        console.log(roledata);
        let newList = roledata.data.data.map((item, index) => {
            return { key: nanoid(), ...item, autharr: JSON.parse(item.autharr) }
        })
        this.setState({ listData: newList, haveData: true })
    }
    render() {
        const { Column } = Table;
        const { listData, isModalVisible, formItemLayout } = this.state
        return (!this.state.haveData ? <p className="loading" style={{ fontSize: "30px" }}>loading</p> : (
            <div id="check-role">
                <Table className="list" dataSource={listData} pagination={{ defaultPageSize: "5" }} >
                    <Column title="id" dataIndex="id" key={nanoid()} />
                    <Column title="名称" dataIndex="name" key={nanoid()} onFilter={ (value, record) => record.name!=="admin" && record.name!=="普通用户"} defaultFilteredValue={["admin","普通用户"]}/>
                    <Column title="创建时间" dataIndex="create_time" key={nanoid()} />
                    <Column title="权限" dataIndex="autharr" key={nanoid()}
                        render={autharr => (
                            <>
                                {autharr.map(tag => (
                                    tag === "" ? "" : <Tag color="blue" key={nanoid()} className="tag">
                                        {tag}
                                    </Tag>
                                ))}
                            </>
                        )}
                    />
                    <Column title="操作" dataIndex="action" key={nanoid()}
                        render={(text, record) => (
                            <Space size="middle">
                                <Button type="primary" onClick={this.showModle(record.id)}>编辑</Button>
                                <Popconfirm placement="top" title='确定删除吗？' onConfirm={this.deleteItem(record.id)} okText="Yes" cancelText="No">
                                    <Button danger >删除</Button>
                                </Popconfirm>
                            </Space>
                        )}
                    />
                </Table>
                <Modal title="编辑角色" visible={isModalVisible} onOk={this.editRole} onCancel={this.hideModle} >
                    <Form  {...formItemLayout} ref={this.formRef}>
                        <Form.Item
                            label="角色名称"
                            name="rolename"
                            rules={[
                                { required: true, whitespace: true, message: '角色名不能为空' }
                            ]}
                        >
                            <Input className="user-in" size='large' ref={this.contentRef} />
                        </Form.Item>
                        <Form.Item
                            label="权限"
                            name="author"
                        >
                            <CheckboxGroup>
                                {
                                    menuList.map((item, index) => {
                                        if (index > 0) {
                                            return <Checkbox value={item.title} key={item.key}>{item.title}</Checkbox>
                                        }
                                    })
                                }
                            </CheckboxGroup>

                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        ))
    }
}
